using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;


using System.Collections.Generic;
using DotNetNuke;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Entities.Modules.Actions;
using DotNetNuke.Security;
using DotNetNuke.Services.Exceptions;
using DotNetNuke.Services.Localization;
using DotNetNuke.Entities.Users;
using DotNetNuke.Security.Roles;
using DotNetNuke.Entities.Modules.Communications;

namespace Jfc007.WebLib
{
    public partial class Documents : PortalModuleBase, IActionable, IModuleListener
    {
        /* Use DocumentInfo.ByteSizeToString
        private string GetSizeLenText ( long byteSize )
        {
            if (byteSize < 1024)
                return String.Format( "{0:D} B", byteSize );
            else if (byteSize < (1024 * 1024))
                return String.Format( "{0:D} KB", byteSize / 1024 );
            else
                return String.Format( "{0:D} MB", byteSize / (1024 * 1024) );
        }
        */

        public void OnModuleCommunication(object s, ModuleCommunicationEventArgs e)
        {
            //lblReceive.Text = e.Text;

        }

        private long GetQuota
        {
            get
            {
                string[] roles = UserInfo.Roles;
                long quota = 0;
                if (roles != null)
                {
                    //RoleManagerModule aa =new RoleManagerModule();
                    RoleController rolesController = new RoleController();
                    for (int i = 0; i < roles.Length; i = i + 1)
                    {
                        long roleQuota = 0;

                        //talvez devesse verificar o nome
                        string roleName = roles[i];
                        RoleInfo roleInfo = rolesController.GetRoleByName(PortalId, roleName);
                        Int64.TryParse(roleInfo.Description, out roleQuota);
                        if (quota < roleQuota)
                            quota = roleQuota;
                    }
                }

                return quota;
            }
        }


        protected void Page_Load(object sender, EventArgs e)
        {







            //objRoleController.GetUserRolesByUsername(PortalId, objUserInfo.Username, Null.NullString)
            //DotNetNuke.Security.Membership.MembershipProvider.Instance().
            //DotNetNuke.Security.Profile.ProfileProvider.Instance(). profile = new 
            // Add columns dynamically
            // DocumentInfo a = new DocumentInfo();

            AddDownloadLink(Localization.GetString("Description.Header", LocalResourceFile), "ctlDownloadLink");
            AddDocumentColumn(Localization.GetString("Category.Header", LocalResourceFile), "Category");
            AddDocumentColumn(Localization.GetString("Keywords.Header", LocalResourceFile), "Keywords");
            AddDocumentColumn(Localization.GetString("Size.Header", LocalResourceFile), "SizeLenText");
            AddDocumentColumn(Localization.GetString("ModifiedDate.Header", LocalResourceFile), "CreatedDate", "{0:d}");

            //Localize the Data Grid
            //Localization.LocalizeDataGrid(grdDocuments, Me.LocalResourceFile)

            // Only read from the cache if the users is not logged in

            string strCacheKey = this.CacheKey + ";anon-doclist";
            List<DocumentInfo> m_documentList = null;
            if (!(Request.IsAuthenticated))
            {
                m_documentList = (List<DocumentInfo>)DataCache.GetCache(strCacheKey);
            }

            DocumentsController controller = new DocumentsController();
            long totalSize = 0;

            if (m_documentList == null)
            {
                m_documentList = controller.GetDocuments(PortalId, this.UserId);
                totalSize = controller.GetTotalSize(PortalId, this.UserId);
            }

            if (!(UserInfo.IsSuperUser))
            {
                long quota = GetQuota;

                lblSize.Text = String.Format(Localization.GetString("UsedSpace.Text", LocalResourceFile),
                    DocumentInfo.ByteSizeToString(totalSize),
                    DocumentInfo.ByteSizeToString(quota));
            }
            else
            {
                lblSize.Visible = false;
            }

            //   Only write to the cache if the user is not logged in
            if (Request.IsAuthenticated)
                DataCache.SetCache(strCacheKey, m_documentList, new TimeSpan(0, 5, 0));

            grdDocuments.DataSource = m_documentList;
            grdDocuments.DataBind();

        }


        public string EditFile(Guid fileId)
        {
            string strFileId = Convert.ToString(fileId);

            //string url = DotNetNuke.Common.Globals.NavigateURL( "" );
            return DotNetNuke.Common.Globals.NavigateURL(TabId, "EditDocuments", "mid=" + Convert.ToString(PortalId), "FileId=" + strFileId);

        }

        #region Optional Interfaces


        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Registers the module actions required for interfacing with the portal framework
        /// </summary>
        /// <value></value>
        /// <returns></returns>
        /// <remarks></remarks>
        /// <history>
        /// </history>
        /// -----------------------------------------------------------------------------
        public ModuleActionCollection ModuleActions
        {
            get
            {
                ModuleActionCollection Actions = new ModuleActionCollection();

                long quota = GetQuota;
                DocumentsController controller = new DocumentsController();
                long totalSize = controller.GetTotalSize(PortalId, this.UserId);
                Boolean isShowEdit = false;

                if ((totalSize <= quota) || (UserInfo.IsSuperUser))
                {
                    isShowEdit = true;
                    string url = DotNetNuke.Common.Globals.NavigateURL(TabId, "EditDocuments", "mid=" + Convert.ToString(PortalId), "");
                    Actions.Add(this.GetNextActionID(), Localization.GetString("AddContent.Action", LocalResourceFile), ModuleActionType.AddContent, "", "", url, false, SecurityAccessLevel.View, isShowEdit, false);

                }
                return Actions;
            }
        }
        public bool IsShowEdit()
        {
            //return DotNetNuke.Security.Permissions.ModulePermissionController.HasModulePermission( ModuleConfiguration.ModulePermissions, "EDIT" );
            return true;
        }

        #endregion
        #region Private Methods
        /// <summary>
        ///  Dynamically adds a column to the datagrid
        /// </summary>
        /// <param name="DataField">The name of the property to read data from</param>
        private void AddDocumentColumn(string DataField)
        {
            AddDocumentColumn(DataField, DataField, "");
        }

        /// <summary>
        ///  Dynamically adds a column to the datagrid
        /// </summary>
        ///  <param name="Title">The name of the property to read data from</param>
        /// <param name="DataField">The name of the property to read data from</param>
        private void AddDocumentColumn(string Title, string DataField)
        {
            AddDocumentColumn(Title, DataField, "");
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="Title">The name of the property to read data from</param>
        /// <param name="DataField">The name of the property to read data from</param>
        /// <param name="Format">Format string for value</param>
        private void AddDocumentColumn(string Title, string DataField, string Format)
        {
            //AddDocumentColumn(Title, DataField, Format, "")
            BoundField objBoundColumn;


            objBoundColumn = new BoundField();

            objBoundColumn.DataField = DataField;
            objBoundColumn.DataFormatString = Format;
            objBoundColumn.HeaderText = Title;

            objBoundColumn.HeaderStyle.CssClass = Title + "Header"; //"NormalBold"
            objBoundColumn.ItemStyle.CssClass = Title + "Cell";  //"Normal"

            this.grdDocuments.Columns.Add(objBoundColumn);

        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="Title">The name of the property to read data from</param>
        /// <param name="DataField">The name of the property to read data from</param>
        /// <param name="Format">Format string for value</param>

        private void AddDownloadLink(string Title, string Name)
        {
            TemplateField objTemplateColumn;
            string strCellPrefix;

            objTemplateColumn = new TemplateField();
            objTemplateColumn.ItemTemplate = new DownloadColumnTemplate(Name, "Download", ListItemType.Item);
            objTemplateColumn.HeaderText = Title;

            strCellPrefix = Title;
            if ((String.IsNullOrEmpty(strCellPrefix)) && (Name == "ctlDownloadLink"))
            {
                strCellPrefix = "Download";
            }

            objTemplateColumn.HeaderStyle.CssClass = strCellPrefix + "Header"; //'"NormalBold"
            objTemplateColumn.ItemStyle.CssClass = strCellPrefix + "Cell"; //"Normal"

            this.grdDocuments.Columns.Add(objTemplateColumn);
        }

#endregion

        protected void GrdDocuments_RowCreated(object sender, GridViewRowEventArgs e)
        {

            if (e.Row.RowType == DataControlRowType.DataRow)
            {

                GridViewRow row = e.Row;

                if (row.FindControl("ctlDownloadLink") != null)
                {
                    DocumentInfo doc = (DocumentInfo)row.DataItem;
                    Guid fileId = doc.FileGuid;
                    HyperLink link = (HyperLink)row.FindControl("ctlDownloadLink");
                    link.Text = doc.FileDescription;
                    //DotNetNuke.Common.Globals.LinkClick(
                    //PortalSettings.ControlPanelVisible = false;
                    //.NavigateURL(Convert.ToInt32(searchTabID), string.Empty, "announcementId=" + articleId);
                    string searchTabID = Convert.ToString(Settings["TabDisplayBinaryData"]);
                    if (!String.IsNullOrEmpty(searchTabID))
                    {
                        //int searchTabID = (int)Settings["TabDisplayBinaryData"];

                        link.NavigateUrl = DotNetNuke.Common.Globals.NavigateURL(Convert.ToInt32(searchTabID), string.Empty, "FileId=" + Convert.ToString(fileId));


                        /*DotNetNuke.Common.Globals.NavigateURL(
                        //Convert.ToInt32(searchTabID), 
                        TabId, "DisplayBinaryData",
                    "mid=" + Convert.ToString( PortalId ), "FileId=" + Convert.ToString( fileId )
                    + "&SkinSrc=" + DotNetNuke.Common.Globals.QueryStringEncode( "[G]" +
                    DotNetNuke.UI.Skins.SkinInfo.RootSkin + "/" + DotNetNuke.Common.Globals.glbHostSkinFolder +
                    "/" + "No Skin" ), "ContainerSrc=" +
                    DotNetNuke.Common.Globals.QueryStringEncode( "[G]" +
                    DotNetNuke.UI.Skins.SkinInfo.RootContainer + "/" +
                    DotNetNuke.Common.Globals.glbHostSkinFolder + "/" + "No Container" ), "" );*/
                        link.Target = "_blank";
                    }
                }
            }
        }
    }

}